package com.zqs.controller;

import com.zqs.entity.UsedCar;
import com.zqs.service.UsedCarService;
import com.zqs.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 卖车获取二手车页
 */
@CrossOrigin
@RestController
@RequestMapping("usedCars")
public class UsedCarController extends BaseController{

    @Autowired
    private UsedCarService usedCarService;

    // 用户添加卖车信息  form-data{title,price,detail,file:汽车图片文件}
    @PostMapping("addUsedCar")
    public JsonResult<Void> addUsedCar(MultipartFile file, UsedCar usedCar, HttpSession session){
        System.out.println("file" + file);
//        String path = session.getServletContext().getRealPath("usedCarImage");
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String prefix = UUID.randomUUID().toString().toUpperCase();
        String filename = "/" + prefix + suffix;
        System.out.println("filename:" + filename);
        String path = "C:\\Users\\张青山\\Desktop\\毕设\\zqs-bs\\src\\main\\resources\\static\\usedCarImage";
        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdir();
        }
        File dest = new File(dir, filename);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Integer uid = getSessionUid(session);
        usedCar.setUid(uid);
        usedCar.setImage("/usedCarImage" + filename);
        usedCarService.add(usedCar);
        return new JsonResult<>(OK);
    }

    // 根据登录用查询卖车记录  不用传参
    @GetMapping("getByUid")
    public JsonResult<List<UsedCar>> getByUid(HttpSession session){
        Integer uid = getSessionUid(session);
        List<UsedCar> datalist = usedCarService.getByUid(uid);
        return new JsonResult<>(OK,datalist);
    }

    // 用户展示二手车列表  不用传参
    @GetMapping("getAll")
    public JsonResult<List<UsedCar>> getAll(){
        List<UsedCar> datalist = usedCarService.getAll();
        return new JsonResult<>(OK,datalist);
    }

    // 根据售卖二手车id更改车辆状态 参数：id
    @GetMapping("update_state")
    public JsonResult<Void> updateState(Integer id,HttpSession session){
        usedCarService.updateStateById(id,getSessionUid(session));
        return new JsonResult<>(OK);
    }
}
